package com.curso.clima.service;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;

public class CargarDatosWs {
	final String conexion = "http://www.webservicex.net/globalweather.asmx";
	
	public WeatherInfo getClima(String ciudad, String pais) throws Exception
	{
		WeatherInfo res=null;
		SoapObject request = new SoapObject("http://www.webserviceX.NET", "GetWeather");

		request.addProperty("CityName", ciudad);
		request.addProperty("CountryName", pais);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.XSD;
		envelope.setOutputSoapObject(request);

		HttpTransportSE transporte = new HttpTransportSE(conexion);
		try{

			transporte.call("http://www.webserviceX.NET/GetWeather", envelope);
			
			Object responseObj = envelope.getResponse();

			Log.e("Clima", responseObj.toString());
			
			String response = null;			
			response = responseObj.toString();
	
			Log.d("Clima", "Response: " +  response);
			
			res = parse(response);

		}catch(Exception e){
			throw e;
		}
		
		return res;
	}

	private WeatherInfo parse(String xml)

	{
		WeatherInfo wi = null;

		try{
			// Parsear temperatura
			String strTemperature = getTagValue(xml, "<Temperature>");

			int indC = strTemperature.indexOf("(");
			String strCel = strTemperature.substring(indC+1, strTemperature.length()-1);
			strCel = strCel.replace("C", "");
				
			wi = new WeatherInfo();
			wi.temperature = Float.parseFloat(strCel);
		}catch(Exception ex){
			Log.e("Clima", "Error Parseando datos.\n" + ex.toString());
		}

		return wi;
	}

	private String getTagValue(String xml, String tag){
		String value = null;

		int start = xml.indexOf(tag);
		int end = xml.indexOf("</", start);			
		if(start > 0 && end >0){

			value = xml.substring(start + tag.length(), end);
		}

		return value.trim();
	}

	public class WeatherInfo{
		public float temperature;
	}
}
